import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

const login_width = 800;
const register_height = 900;

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    icon: icon,
    width: login_width,
    height: register_height,
    show: false,
    transparent: true,
    autoHideMenuBar: true,
    titleBarStyle: 'hidden',
    resizable: false,
    frame: true,
    mediaAccess: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      contextIsolation: false,
      webSecurity: false,
    }
  })

  ipcMain.on('toMain', (event, args) => {
    mainWindow.setResizable(true)
    mainWindow.setSize(((args.screenWidth / 5) * 3) + 250, 800)
    mainWindow.setMinimumSize(((args.screenWidth / 5) * 3) + 250, 800)
    mainWindow.center();
    mainWindow.setMaximizable(true)
    mainWindow.setMaximumSize(((args.screenWidth / 5) * 3) + 300, 900)
  })

  ipcMain.on('minimizing', (event, args) => {
    event.preventDefault(); // 阻止默认最小化行为
    mainWindow.minimize(); // 最小化到任务栏
  })

  ipcMain.on('expandWindow', (event, args) => {
    let defaultSize = mainWindow.getSize();
    let maxSize = mainWindow.getMaximumSize();
    if (defaultSize[0] === (((args.screenWidth / 5) * 3) + 250) && defaultSize[1] === 800) {
      mainWindow.setResizable(true)
      mainWindow.setSize(((args.screenWidth / 5) * 3) + 300, 900)
    } else if (maxSize[0] === (((args.screenWidth / 5) * 3) + 300) && maxSize[1] === 900) {
      mainWindow.setResizable(true)
      mainWindow.setSize(((args.screenWidth / 5) * 3) + 250, 800)
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    // 窗口调试
    mainWindow.webContents.openDevTools()
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // 初始化账户管理器
  const accountManager = require('../class');
  accountManager.initialize();

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 检查自动登录
ipcMain.handle('check-auto-login', async (event) => {
  try {
    const accountManager = require('../class');
    const result = await accountManager.initialize();

    if (result.success && result.autoLogin) {
      const currentUser = accountManager.getCurrentUser();
      const token = accountManager.dataStorage.getToken();

      return {
        success: true,
        autoLogin: true,
        user: {
          username: currentUser?.getUserName(),
          userId: currentUser?.getUserId()
        },
        token: token
      };
    }

    return { success: false, autoLogin: false };
  } catch (error) {
    console.error('自动登录检查错误:', error);
    return { success: false, message: error.message || '自动登录检查失败' };
  }
});

// 处理登录请求
ipcMain.handle('login', async (event, loginData) => {
  try {
    const { userId, password, rememberMe } = loginData;
    console.log(userId, password, rememberMe);// 接收正常
    const accountManager = require('../class');
    const result = await accountManager.login(userId, password, rememberMe);
    return result;
  } catch (error) {
    console.error('登录处理错误:', error);
    return { success: false, message: error.message || '登录处理失败' };
  }
});

// 处理注册请求
ipcMain.handle('register', async (event, data) => {
  try {
    const { userId, password } = data;
    console.log(userId, password); // 接收正常
    const accountManager = require('../class');
    const result = await accountManager.register(userId, password);
    return result;
  } catch (error) {
    console.error('注册处理错误:', error);
    return { success: false, message: error.message || '注册处理失败' };
  }
});

// 处理登出请求
ipcMain.handle('logout', async (event) => {
  try {
    const accountManager = require('../class');
    const result = accountManager.logout();
    return result;
  } catch (error) {
    console.error('登出处理错误:', error);
    return { success: false, message: error.message || '登出处理失败' };
  }
});

// 处理第三方绑定
ipcMain.handle('bind-third-party', async (event, brandName, authCode) => {
  try {
    const accountManager = require('../class');
    const result = await accountManager.bindThirdPartyBrand(brandName, authCode);
    return result;
  } catch (error) {
    console.error('第三方绑定错误:', error);
    return { success: false, message: error.message || '第三方绑定失败' };
  }
});

// 处理第三方解绑
ipcMain.handle('unbind-third-party', async (event, brandName) => {
  try {
    const accountManager = require('../class');
    const result = await accountManager.unbindThirdPartyBrand(brandName);
    return result;
  } catch (error) {
    console.error('第三方解绑错误:', error);
    return { success: false, message: error.message || '第三方解绑失败' };
  }
});

// 获取绑定信息
ipcMain.handle('get-bindings', async (event) => {
  try {
    const accountManager = require('../class');
    const result = await accountManager.loadUserBindings();
    return result;
  } catch (error) {
    console.error('获取绑定信息错误:', error);
    return { success: false, message: error.message || '获取绑定信息失败' };
  }
});

// 获取授权码
ipcMain.handle('get-authorization-code', async (event, userId) => {
  try {
    const accountManager = require('../class');
    const result = await accountManager.getAuthorizationCode(userId);
    return result;
  } catch (error) {
    console.error('获取授权码错误:', error);
    return { success: false, message: error.message || '获取授权码失败' };
  }
});

// 刷新token
ipcMain.handle('refresh-token', async (event) => {
  try {
    const accountManager = require('../class');
    const result = await accountManager.refreshAccessToken();
    return result;
  } catch (error) {
    console.error('刷新token错误:', error);
    return { success: false, message: error.message || '刷新token失败' };
  }
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
